package com.disdr.datacenter;

import cn.hutool.json.JSONObject;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Set;

public class HttpJsonUtil {

    public static void main(String[] args) {

        String uri = "https://ros-upload.xiaohongshu.com/spectrum/u7cziTW8_pOfGTMIf3ijeSToeRfeoeMKxRQ0ER-PlVhV6dY";
        File file = new File("E:\\24a5a264b07b305895870b8d345176f9.jpg");
        sendPut(uri,file);
    }

    public static String sendPut(String uri, File file){
        HttpURLConnection connection = null;
        try {
            URL url = new URL(uri);
            connection = (HttpURLConnection)url.openConnection();
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setRequestMethod("PUT");
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);

            //设置header
            connection.setRequestProperty("Content-Type","image/jpeg");
            connection.setRequestProperty("x-cos-security-token","NMT3kzjY79P2aXgGOhlawq5ukOw:eyJkZWFkbGluZSI6MTY5MzgwMzAzMiwiYWxsb3dQcmVmaXhlcyI6WyJ1N2N6aVRXOF9wT2ZHVE1JZjNpamVTVG9lUmZlb2VNS3hSUTBFUi1QbFZoVjZkWSJdfQ");
            //connection.setRequestProperty("Content-Length", "853465");

            connection.connect();

            //读取文件流
            int size = (int) file.length();
            byte[] data = new byte[size];
            FileInputStream fis = new FileInputStream(file);
            OutputStream out = connection.getOutputStream();
            fis.read(data, 0, size);
            //写入文件名
            out.write(file.getName().trim().getBytes());
            //写入分隔符
            out.write('|');
            //写入图片流
            out.write(data);

            out.flush();
            out.close();

            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String lines;
            StringBuffer sb = new StringBuffer("");
            while((lines=reader.readLine())!=null){
                lines = new String(lines.getBytes(StandardCharsets.UTF_8));
                sb.append(lines);
            }
            reader.close();
            connection.disconnect();
            return sb.toString();
        }catch (Exception e){
            System.out.println(e);
        }finally {
            if(connection != null){
                try {
                    connection.disconnect();
                }catch (Exception e){}
            }
        }
        return null;
    }


}

